<template>
  <el-card shadow="never">
    <div v-if="showTitle" slot="header">
      <span>结算方式</span>
    </div>
    <skus-table
      :showTotal="false"
      :showSelectCol="false"
      :showPagination="false"
      :columns="tableColumn"
      :dataSource="tableList"
      :tableHeight="270"
      @handleCancelSelect="handleCancelSelect"
      @handleSelectChange="handleSelectChange"
      @handleRowChange="handleRowChange"
    >
      <div v-if="!readonly" slot="content_context" style="margin-bottom: 5px">
        <el-button size="mini" type="primary" @click="handleAddRow"
          >添加行</el-button
        >
      </div>
    </skus-table>
  </el-card>
</template>
<script>
import SkusTable from '@/components/skusTable';
import { ACCEPT_RATIO_SELECT_LIST } from '@/pages/supplier/constants/common';
import { querySysTypeByDictIdsService } from '@/api/supplier/components';
import { list2Obj } from '@/pages/supplier/utils';
import { toFixedCustomize } from '@/utils/bizUtils';

export default {
  components: {
    SkusTable
  },
  props: {
    dataSource: {
      type: Array,
      default: () => {
        return []
      }
    },
    readonly: {
      type: Boolean,
      default: false
    },
    showTitle: {
      type: Boolean,
      default: true
    },
    operation: {
      type: Array
    }
  },
  data () {
    return {
      key: 0,
      tableColumn: [],
      tableList: [],
      settlementOption: [],
    };
  },
  watch: {
    dataSource: {
      handler (newVal) {
        this.tableList = newVal
        if (this.tableList.length == 0 && !this.readonly) {
          this.handleAddRow()
        } else {
          this.tableList.forEach(item => {
            if (item.settlementType == 40922 || item.settlementType == 40923) {
              item.disable = true;
            }
          })
        }
      },
      immediate: true,
      deep: true
    },
    tableList: {
      handler (newVal, oldVal) {
        if (newVal) {
          const settlementTypes = newVal.map(item => item.settlementType)
          this.settlementOption.forEach(item => {
            if (settlementTypes.includes(item.value)) {
              item.disabled = true;
            } else {
              item.disabled = false;
            }
          });
          this.$emit('change', { value: newVal, prop: 'supplierSettlementBillList' })
        }
      },
      immediate: true,
      deep: true
    },
  },
  created () {
    this.queryOptionsByMaster()
  },
  methods: {
    // 初始化表列
    initTableCloumn () {
      console.log(this.operation)
      if (this.readonly) {
        if (this.operation) {
          this.tableColumn = [
            {
              key: 'settlementType',
              title: '结算方式',
              children: [
                {
                  title: '原值',
                  key: 'settlementTypeOld',
                  width: 80,
                  formatter: (row, columns, cellValue) => {
                    return list2Obj(this.settlementOption)[cellValue];
                  }
                },
                {
                  title: '现值',
                  key: 'settlementType',
                  width: 80,
                  formatter: (row, columns, cellValue) => {
                    return list2Obj(this.settlementOption)[cellValue];
                  }
                }
              ]
            },
            {
              key: 'useRatio',
              title: '使用比例（%）',
              children: [
                {
                  title: '原值',
                  key: 'useRatioOld',
                  width: 80,
                  formatter: (row, columns, cellValue) => {
                    return list2Obj(ACCEPT_RATIO_SELECT_LIST)[cellValue];
                  }
                },
                {
                  title: '现值',
                  key: 'useRatio',
                  width: 80,
                  formatter: (row, columns, cellValue) => {
                    return list2Obj(ACCEPT_RATIO_SELECT_LIST)[cellValue];
                  }
                }
              ]
            },
            {
              key: 'singlePayment',
              title: '单笔限额（元）',
              children: [
                {
                  title: '原值',
                  key: 'singlePaymentOld',
                  width: 80,
                },
                {
                  title: '现值',
                  key: 'singlePayment',
                  width: 80,
                }
              ]
            },
            {
              key: 'annualCumulativeLimit',
              title: '年度累计限额（元）',
              children: [
                {
                  title: '原值',
                  key: 'annualCumulativeLimitOld',
                  width: 80,
                },
                {
                  title: '现值',
                  key: 'annualCumulativeLimit',
                  width: 80,
                }
              ]
            },
            {
              key: 'rateInterest',
              title: '我司承担贴息利率(%)',
              headTip: '此贴息利率为实际我公司需要承担部分的贴息利率，使用商承结算的金额乘以此利率即可算出最终贴息金额。',
              children: [
                {
                  title: '原值',
                  key: 'rateInterestOld',
                  width: 80,
                },
                {
                  title: '现值',
                  key: 'rateInterest',
                  width: 80,
                }
              ]
            },
            {
              key: 'acceptPeriod',
              title: '承兑期限（天）',
              children: [
                {
                  title: '原值',
                  key: 'acceptPeriodOld',
                  width: 80,
                },
                {
                  title: '现值',
                  key: 'acceptPeriod',
                  width: 80,
                }
              ]
            },
            {
              key: 'freeUseRatio',
              title: '免息使用比例',
              children: [
                {
                  title: '原值',
                  key: 'freeUseRatioOld',
                  width: 80,
                  formatter: (row, columns, cellValue) => {
                    return list2Obj(ACCEPT_RATIO_SELECT_LIST)[cellValue];
                  }
                },
                {
                  title: '现值',
                  key: 'freeUseRatio',
                  width: 80,
                  formatter: (row, columns, cellValue) => {
                    return list2Obj(ACCEPT_RATIO_SELECT_LIST)[cellValue];
                  }
                }
              ]
            },
            {
              key: 'freeAcceptPeriod',
              title: '免息承兑期限(天)',
              children: [
                {
                  title: '原值',
                  key: 'freeAcceptPeriodOld',
                  width: 80
                },
                {
                  title: '现值',
                  key: 'freeAcceptPeriod',
                  width: 80,
                }
              ]
            },
            {
              key: 'discountTaxRate',
              title: '贴息部分补税税率(%)',
              children: [
                {
                  title: '原值',
                  key: 'discountTaxRateOld',
                  width: 80
                },
                {
                  title: '现值',
                  key: 'discountTaxRate',
                  width: 80,
                }
              ]
            },
            {
              key: 'fixedDays',
              title: '固定天数(天)',
              width: 120,
            },
            {
              key: 'fixedRateInterest',
              title: '固定贴息年利率(%)',
              width: 150,
            }
          ];
        } else {
          this.tableColumn = [
            {
              key: 'settlementType',
              title: '结算方式',
              formatter: (row, columns, cellValue) => {
                return list2Obj(this.settlementOption)[cellValue];
              }
            },
            {
              key: 'useRatio',
              title: '使用比例（%）',
              formatter: (row, columns, cellValue) => {
                return list2Obj(ACCEPT_RATIO_SELECT_LIST)[cellValue];
              }
            },
            { key: 'singlePayment', title: '单笔限额（元）' },
            { key: 'annualCumulativeLimit', title: '年度累计限额（元）' },
            { key: 'rateInterest', title: '我司承担贴息利率(%)' },
            { key: 'acceptPeriod', title: '承兑期限（天）' },
            {
              key: 'freeUseRatio',
              title: '免息使用比例',
              formatter: (row, columns, cellValue) => {
                return list2Obj(ACCEPT_RATIO_SELECT_LIST)[cellValue];
              }
            },
            {
              key: 'freeAcceptPeriod',
              title: '免息承兑期限(天)',
            },
            {
              key: 'discountTaxRate',
              title: '贴息部分补税税率(%)',
            },
            {
              key: 'fixedDays',
              title: '固定天数(天)',
            },
            {
              key: 'fixedRateInterest',
              title: '固定贴息年利率(%)',
              width: 150,
            }
          ];
        }
      } else {
        this.tableColumn = [
          { key: 'settlementType', title: '结算方式', type: 'selectChange', options: this.settlementOption, width: 100, required: true },
          {
            key: 'useRatio',
            title: '使用比例(%)',
            width: 110,
            required: true,
            render: (h, { row }) => {
              const options = [40922, 40923].includes(row.settlementType) ? ACCEPT_RATIO_SELECT_LIST : ACCEPT_RATIO_SELECT_LIST.slice(1)
              return <el-select v-model={row.useRatio} onChange={val => { this.handleSelectChange({ row, val }) }} >
                {
                  options.map(item => {
                    return (
                      <el-option key={item.value} value={item.value} label={item.label}/>
                    )
                  })
                }
              </el-select>
            }
          },
          {
            key: 'singlePayment',
            title: '单笔限额(元)',
            width: 160,
            render: (h, { row }) => {
              return <el-input-number
                v-model={row.singlePayment}
                controls-position="right"
                min={0}
                max={99999999}
                disabled={row.disable}
              />
            }
          },
          {
            key: 'annualCumulativeLimit',
            title: '年度累计限额(元)',
            width: 160,
            render: (h, { row }) => {
              return <el-input-number
                v-model={row.annualCumulativeLimit}
                controls-position="right"
                min={0}
                max={99999999}
                disabled={row.disable}
              />
            }
          },
          {
            key: 'rateInterest',
            title: '我司承担贴息利率(%)',
            headTip: '此贴息利率为实际我公司需要承担部分的贴息利率，使用商承结算的金额乘以此利率即可算出最终贴息金额。',
            width: 150
          },
          {
            key: 'acceptPeriod',
            title: '承兑期限(天)',
            width: 160,
            render: (h, { row }) => {
              return <el-input-number
                v-model={row.acceptPeriod}
                controls-position="right"
                min={[40922, 40923].includes(row.settlementType) ? 0 : 3}
                max={365}
                precision={0}
                disabled={row.disable}
                onChange={val => { this.handleSelectChange({ row, val }) }}
              />
            }
          },
          {
            key: 'freeUseRatio',
            title: '免息使用比例',
            width: 110,
            render: (h, { row }) => {
              return <el-select disabled={row.disable} v-model={row.freeUseRatio} onChange={val => { this.handleSelectChange({ row, val }) }}>
                {
                  ACCEPT_RATIO_SELECT_LIST.map(item => {
                    return (
                      <el-option key={item.value} value={item.value} label={item.label} />
                    )
                  })
                }
              </el-select>
            }
          },
          {
            key: 'freeAcceptPeriod',
            title: '免息承兑期限(天)',
            width: 160,
            render: (h, { row }) => {
              return <el-input-number
                v-model={row.freeAcceptPeriod}
                disabled={row.disable}
                controls-position="right"
                min={0}
                max={365}
                precision={0}
                onChange={val => { this.handleSelectChange({ row, val }) }}
              />
            }
          },
          {
            key: 'discountTaxRate',
            title: '贴息部分补税税率(%)',
            type: 'inputNumChange',
            required: true,
            width: 160,
            minVal: 0,
            maxVal: 30,
            precision: 4,
          },
          {
            key: 'fixedDays',
            title: '固定天数(天)',
            width: 110,
          },
          {
            key: 'fixedRateInterest',
            title: '固定贴息年利率(%)',
            width: 140,
          },
          { key: 'action', title: '操作', fixd: 'right' },
        ];
      }
    },
    // 通过主数据获取 结算方式
    async queryOptionsByMaster () {
      const { result } = await querySysTypeByDictIdsService({ itemIds: '10173' })
      if (result && result[10173]) {
        this.settlementOption = result[10173].map(item => ({
          value: item.sysTypeId,
          label: item.sysTypeName
        }))
      }
      this.initTableCloumn()
    },
    /* 删除按钮事件 */
    handleCancelSelect ({ row, index }) {
      if (this.tableList.length > 1) {
        this.tableList.splice(index, 1);
      }
    },
    handleRowChange (row, val, columnName) {
      row.rateInterest = this.getRateInterest(row)
    },
    handleSelectChange (data) {
      const { row, columnName } = data;
      if (columnName == 'settlementType') {
        row.useRatio = '';
        row.singlePayment = 0;
        row.annualCumulativeLimit = 0;
        row.rateInterest = 0;
        // 商业承兑：40919 信用凭证：40920 银行承兑：40921 转账：40922 现金：40923
        if (row.settlementType == 40922 || row.settlementType == 40923) {
          row.acceptPeriod = 0;
          row.freeAcceptPeriod = 0;
          row.freeUseRatio = 0;
          row.discountTaxRate = 0;
          row.fixedDays = 0; // 固定天数(天)
          row.fixedRateInterest = 0; // 固定贴息年利率（%）
          row.disable = true;
        } else if (row.settlementType == 40921) {
          row.acceptPeriod = 3;
          row.fixedDays = 360; // 固定天数(天)
          row.fixedRateInterest = 1.9; // 固定贴息年利率（%）
          row.disable = false;
        } else {
          row.acceptPeriod = 3;
          row.fixedDays = 360; // 固定天数(天)
          row.fixedRateInterest = 4; // 固定贴息年利率（%）
          row.disable = false;
        }
      } else {
        row.rateInterest = this.getRateInterest(row)
      }
    },
    // 添加行
    handleAddRow () {
      if (this.tableList.length < 5) {
        this.tableList.push({
          key: ++this.key,
          settlementType: '',
          useRatio: '', // 使用比例（%）
          singlePayment: 0,
          annualCumulativeLimit: 0,
          rateInterest: 0, // 我司承担贴息利率（%）
          acceptPeriod: 0, // 承兑期限（天）
          freeUseRatio: 0, // 免息使用比例（%）
          freeAcceptPeriod: 0, // 免息承兑期限（天）
          discountTaxRate: 0, // 贴息部分补税税率(%)
          fixedDays: 360, // 固定天数(天)
          fixedRateInterest: 4, // 固定贴息年利率（%）
        })
      }
    },
    getValidate () {
      if (this.tableList.some(item => !item.settlementType || !item.useRatio || (item.discountTaxRate != 0 && !item.discountTaxRate))) {
        this.$message.error('请将合同信息下的结算方式必填项填写完整')
        return true;
      }
      const useRatioSum = this.tableList.reduce((sum, e) => sum + Number(e.useRatio || 0), 0)
      if (useRatioSum !== 100) {
        this.$message.error('结算方式使用比例之和需要等于100%')
        return true;
      }
      if (this.tableList.some(item => (item.settlementType == 40919 || item.settlementType == 40920 || item.settlementType == 40921) && !item.acceptPeriod)) {
        this.$message.error('结算方式为商业承兑、银行承兑、信用凭证时，承兑期限必填且不能小于3')
        return true;
      }
      return false;
    },
    getData () {
      return this.tableList
    },
    // 计算我司承担贴息利率
    // 我司承担贴息利率 = 固定贴息年利率/固定天数*（承兑期限-免息承兑期限*免息使用比例）*使用比例*(1+贴息部分补税税率)；
    // rateInterest = fixedRateInterest/fixedDays * (acceptPeriod - freeAcceptPeriod * freeUseRatio) * useRatio * (1 + discountTaxRate)
    getRateInterest (item) {
      if (!item.discountTaxRate && item.discountTaxRate !== 0) {
        return;
      }
      // 固定贴息年利率/固定天数
      const fixedVal = (item.fixedRateInterest / 100) / item.fixedDays
      // 承兑期限-免息承兑期限*免息使用比例
      const acceptVal = item.acceptPeriod - item.freeAcceptPeriod * (item.freeUseRatio / 100)
      // *(1+贴息部分补税税率)
      const useRatioVal = 1 + item.discountTaxRate / 100
      const finalResult = fixedVal * acceptVal * useRatioVal * 100
      return toFixedCustomize(finalResult, 10000)
    }
  },
};
</script>
<style scoped>
.page-footer {
  margin-top: 10px;
}
</style>
